/**
 * jQuery EasyUI 表单渲染自定义
 * TiddlerCJ 
 */
(function($){
	var formFn = {
			html: null,
			fTableName: null,
			count: 0,
			trDom:'<tr><td class="fLable"></td><td class="fInput"></td></tr>',
			/*设置表单名称*/
			_setFormName: function(name){
				 $("#fName").text(name || '未知表单名称');
			},
			_formartInoutHtml:function(row){
				var _this = this;
				var fieldName = row.fieldName;
				var colspan= row.fieldCol || 1;
				var label = row.fieldTitle || row.fieldName;
				var dataOpts = [];
				var validType = [];
				
				/*ValidType验证*/
				$.each((row.fieldValidType || '').split(","), function(i,val){
					if(val){ validType.push(val); }
				});
				validType = validType.join(",");
				if(validType!=''){
					dataOpts.push("validType:["+ validType  +"]");
				}
				
				$.each((row.fieldRequired || '').split(","), function(i,val){
					if(val){ dataOpts.push(val);}
				});
				
				var item = '';
				switch (row.fieldPlug) {
					case '隐藏属性':
						item = '<input type="hidden"  name="'+ row.fieldName +'" />';
						break;
					case '附件上传':
						var dom = _this.trDom,
						$dom = $(dom);
						dataOpts.push("upload:{auto:false,height:250}");
						item = '<input class="easyui-layuiupload" name="'+ row.fieldName +'" style="width:100%;" />';
						$dom.find(".fLable").text(label+"：");
						$dom.find(".fInput").attr("colspan",colspan).html(item);
						$dom.find(".formItem").attr("data-options",dataOpts.join(","));
						item = $dom.html();
						break;
						break;
					case '数据字典':
						break;
					case '单行文本':
					case '多行文本':
						var dom = _this.trDom,
						$dom = $(dom);
						if(row.fieldPlug=='多行文本'){
							dataOpts.push("multiline:true");
							dataOpts.push("height:60");
						}
						item = '<input type="text" class="easyui-validatebox easyui-textbox formItem" name="'+ row.fieldName +'" style="width:100%;" ></input>';
						$dom.find(".fLable").text(label+"：");
						$dom.find(".fInput").attr("colspan",colspan).html(item);
						$dom.find(".formItem").attr("data-options",dataOpts.join(","));
						item = $dom.html();
						break;
					case '数字输入':
						var dom = _this.trDom,
						$dom = $(dom);
						item = '<input type="text" class="easyui-numberbox easyui-validatebox formItem" name="'+ row.fieldName +'"  style="width:100%;" ></input>';
						$dom.find(".fLable").text(label+"：");
						$dom.find(".fInput").attr("colspan",colspan).html(item);
						$dom.find(".formItem").attr("data-options",dataOpts.join(","));
						item = $dom.html();
						break;
					case '日期选择':
					case '时间选择':
						if(row.fieldPlug=='时间选择'){
							dataOpts.push("showSeconds:false");
							item = '<input type="text" class="easyui-validatebox easyui-datetimebox formItem" name="'+ row.fieldName +'"  style="width:100%;" ></input>';
						}else{
							item = '<input type="text" class="easyui-validatebox easyui-datebox formItem" name="'+ row.fieldName +'"  style="width:100%;" ></input>';
						}
						var dom = _this.trDom,
						$dom = $(dom);
						$dom.find(".fLable").text(label+"：");
						$dom.find(".fInput").attr("colspan",colspan).html(item);
						$dom.find(".formItem").attr("data-options",dataOpts.join(","));
						item = $dom.html();
						break;
					case '人员选择':
						var dom = _this.trDom,
						$dom = $(dom);
						item = '<input type="text" class="easyui-validatebox easyui-userbox formItem" name="'+ row.fieldName +'" style="width:100%;" ></input>';
						$dom.find(".fLable").text(label+"：");
						$dom.find(".fInput").attr("colspan",colspan).html(item);
						$dom.find(".formItem").attr("data-options",dataOpts.join(","));
						item = $dom.html();
						break;
					case '部门选择':
						var dom = _this.trDom,
						$dom = $(dom);
						item = '<input type="text" class="easyui-validatebox easyui-orgbox formItem" name="'+ row.fieldName +'" style="width:100%;" ></input>';
						$dom.find(".fLable").text(label+"：");
						$dom.find(".fInput").attr("colspan",colspan).html(item);
						$dom.find(".formItem").attr("data-options",dataOpts.join(","));
						item = $dom.html();
						break;
					case '自动编号':
						var dom = _this.trDom,
						$dom = $(dom);
						dataOpts.push("buttonText:''");
						item = '<input  class="easyui-autoCode formItem"  name="'+ row.fieldName +'" style="width:100%;" />';
						$dom.find(".fLable").text(label+"：");
						$dom.find(".fInput").attr("colspan",colspan).html(item);
						$dom.find(".formItem").attr("data-options",dataOpts.join(","));
						item = $dom.html();
						break;
					case '关联子表':
						var dom = _this.trDom,
						$dom = $(dom);
						item = '<table class="easyui-jform formTable formItem" name="'+ row.fieldName +'" align="center" style="width:100%;"><tbody></tbody></table>';
						$dom.find(".fLable").text(label+"：");
						$dom.find(".fInput").attr("colspan",colspan).html(item);
						$dom.find(".formItem").attr("data-options",dataOpts.join(","));
						item = $dom.html();
						break;
					case '动作按钮':
						var dom = _this.trDom,
						$dom = $(dom);
						item = '<div style="width:100%;"><a href="#" class="row-click" motion="add" style="width:40px;height:30px;">+</a>&nbsp;&nbsp;<a href="#" class="row-click" motion="del"  style="width:40px;height:30px;">-</a></div>';
						$dom.find(".fLable").text(label+"：");
						$dom.find(".fInput").attr("colspan",colspan).html(item);
						$dom.find(".formItem").attr("data-options",dataOpts.join(","));
						item = $dom.html();
						break;
					default:
						break;
				}
				return item;
			},
			/*创建表单html*/
			_createFormHtml:function(rows,lineCount){
				var _this = this;
				_this.count = 0 ;
				var target = _this.target;
				var html = [];
				html.push('<tr>');
				var row = null;
    			for(var i=0,len=rows.length ;i<len; i++){
    				row = rows[i];
    				if(row.fieldEnabled!='Y'){ continue; }
    				
    				if(row.fieldLine=='Y'){
    					html.push("###");
    				}
    				html.push(_this._formartInoutHtml(row));
    				
    				_this.count ++;
    				
    				if(row.fieldPlug=='隐藏属性'){
	    				_this.count--;
    				}
    				if(_this.count % lineCount===0){
    					html.push("###");
    				}
    			}
    			html.push('</tr>');
    			html = html.join('');
    			
    			html= html.replace(new RegExp('###','g'),"</tr><tr>");
    			
    			_this.html = html;
    			
    			var $target = $(target);
    			
    			
    			$target.find("tbody").append(html);
    			
    			setTimeout(function(){
	    			$.parser.parse($target);
    			},100);
    			
    			_this.formartOrg($target);
    			
    			_this.bindClick($target);
    			
    			$target.find(".formTable").attr("name",_this.fTableName);
			},
			/*绑定点击事件*/
			bindClick:function($obj){
				var _this = this;
				function bind(item,$target){
					var $this = $(item),motion = $this.attr("motion");
					if(motion=='add' && _this.html){
						$target.find("tbody").append(_this.html);
						
						$.parser.parse($target);
						
						$obj.find(".row-click").unbind().on("click",function(){
							bind(this,$obj);
						});
					}
					if(motion=='del'){
						var len = $target.find("a[motion=del]").length;
						if(len>1){
							$this.parents("tr:first").remove();
						}else{
							$.messager.show({ title:'温馨提示', msg:'基础模板行不允许删除!', timeout:3000, showType:'slide' });
						}
					}
					
				}
				
				$obj.find(".row-click").on("click",function(){
					bind(this,$obj);
				});
				
				bind();
			},
			formartOrg:function($obj){
				$obj.find(".easyui-orgbox").combotreegrid({
				    panelWidth:350, delay: 500,  mode: 'remote',   
				    url:'/console/com.fs.base.pojo.Org/list',
					idField: 'orgNo', 
		           	missingMessage:'必填项',
					treeField: 'orgName',
					sortName:'orgOrder',
					onSelect:function(row){},
					sortOrder:'asc',
		            queryParams:{isTreeGrid:'true', treeId:'id', treePid:'parentId' }, 
		            columns:[[    
	  	                {field:'orgName',width:250, title:'组织名称' }
	  		         	,{field:'orgType', width:70, title:'分类' }
	  	            ]]
				});
				
				$obj.find(".easyui-userbox").combotree({
				    url:'/console/combobox?valueField=id&textField=nickName&modleName=user',
		           	missingMessage:'必填项'
				});  
			},
			/*异步获取表单配置json*/
			_ajaxDbconfig:function(){
				var opts = this.defaults;
				var _this = this;
				$.getJSON(opts.url, {formId: opts.formid} ,function(res){
					//console.log(res);
					_this.fTableName = res.fTableName || '';
					if(res && res.total>0){
						_this._setFormName(res.fName);
					}
					_this._createFormHtml(res.rows,res.lineCount);
				});
			},
			init: function (target,opts){
				this.defaults = opts ; 
				this.target = target ;
		        this._ajaxDbconfig();
		        return $(target);
			},
			target: null,
			defaults: {}
		};
	
	
	$.fn.jform = function(options, param){
        if (typeof options == 'string'){
            var method = $.fn.jform.methods[options];
            if (method){
                return method(this, param);
            }
        }
        options = options || {};
        return this.each(function(){
            var state = $.data(this, 'jform');
            if (state){
                $.extend(state.options, options);
            } else {
            	var _opts = $.extend({}, $.fn.jform.defaults, $.fn.jform.parseOptions(this), options);
                state = $.data(this, 'jform', { options: _opts });
                formFn.init(this,_opts);
            }
        });
    };
    
    $.fn.jform.methods = {
        options: function(jq){
            return $.data(jq[0], 'jform').options;
        },
        getFormId: function(jq){
            return $.data(jq[0], 'jform').options.formid;
        }
    };
    
    $.fn.jform.parseOptions = function(target){
        return $.extend({}, $.parser.parseOptions(target, ['formid','height','width']));
    };
    
    /**
     * 默认参数
     */
    $.fn.jform.defaults = {
        width: 'auto',
        height: 22,
        formid: '',
        url: '/console/jForm/rewrite/getDbGrid',
        trDom:'<tr><td class="fLable"></td><td class="fInput"></td></tr>',
        onChange:function(newValue,oldValue){
        }
    };
    
    $.parser.plugins.push("jform");
})(jQuery);